package com.example.webdownloadserver.base;

import com.example.webdownloadserver.common.TaskConstants;
import com.example.webdownloadserver.constants.TaskCenterConstants;
import com.example.webdownloadserver.core.ITaskProcess;
import com.example.webdownloadserver.core.TaskHandlerUtil;
import com.example.webdownloadserver.service.TaskCenterService;
import com.example.webdownloadserver.vo.TaskCenter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class TaskUploadHandleThread implements Runnable {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private TaskCenterService taskCenterService;
	
	private TaskCenter taskCenter;
	

	public TaskUploadHandleThread(TaskCenterService taskCenterService, TaskCenter taskCenter) {
		this.taskCenterService = taskCenterService;
		this.taskCenter = taskCenter;
	}

	@Override
	public void run() {
		boolean flag = false;
		try {
			if (TaskConstants.TASK_TYPE_U.equals(taskCenter.getTaskType())) {
				upload(taskCenter);
			}
			flag = true;
		}catch (TaskJobException e) {
			taskCenter.setTaskStatus(TaskCenterConstants.TASK_STATUS_FAIL);
			taskCenter.setTaskCleanFlag(TaskCenterConstants.TASK_CLEAN_FLAG_CAN);
			taskCenter.setTaskRemark(e.getMessage());
		}catch (Exception e) {
			logger.error("处理上传任务异常", e);
			taskCenter.setTaskStatus(TaskCenterConstants.TASK_STATUS_FAIL);
			taskCenter.setTaskCleanFlag(TaskCenterConstants.TASK_CLEAN_FLAG_CAN);
			taskCenter.setTaskRemark("找不到上传任务处理类");
		}
		if(!flag) {
			taskCenterService.update(taskCenter);
		}
	}

	public void upload(TaskCenter taskCenter) {
		ITaskProcess iface = (ITaskProcess) TaskHandlerUtil.uploadHandlerBeanMap.get(taskCenter.getTaskHandler());
		iface.handler(taskCenter);
	}

}